package com.gdit.framework.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * cookie操作
 * 
 * @author EX-HUANGBIN001
 * @2012-6-26
 */
public class CookieUtil {

	/**
	 * 获取cookie值
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookie( HttpServletRequest request , String name ) {
		Cookie cookies[] = request.getCookies();
		if (cookies == null || name == null || name.length() == 0) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			if (name.equals(cookies[i].getName()) && request.getServerName().equals(cookies[i].getDomain())) {
				return cookies[i];
			}
		}
		return null;
	}

	/***
	 * 删除cookie
	 * 
	 * @param request
	 * @param response
	 * @param cookie
	 */
	public static void deleteCookie( HttpServletRequest request , HttpServletResponse response , Cookie cookie ) {
		if (cookie != null) {
			cookie.setPath("/");
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	// 删除cookie
	public static Cookie deleteCookie(  HttpServletRequest request,HttpServletResponse response ,String name ) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					cookie.setValue("");
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					return cookie;
				}
			}
		}
		return null;
	}

	/**
	 * 设置cookie
	 * 
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void setCookie( HttpServletResponse response , String name , String value ) {
		Cookie cookie = new Cookie(name, value == null ? "" : value);
		cookie.setMaxAge(0x278d00);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	private static String getPath( HttpServletRequest request ) {
		String path = request.getContextPath();
		return (path == null || path.length() == 0) ? "/" : path;
	}

}